const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const path = require('path');
const sqlite3 = require('sqlite3').verbose();
const bcrypt = require('bcryptjs');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const fs = require('fs');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件配置
app.use(helmet());
app.use(cors());
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.set('view engine', 'ejs');

// 会话配置
app.use(session({
    secret: process.env.SESSION_SECRET || 'minecraft-panel-secret',
    resave: false,
    saveUninitialized: false,
    cookie: { secure: false } // 生产环境应该设置为true
}));

// 数据库初始化
const db = new sqlite3.Database('./database.sqlite');

// 创建数据库表
function initDatabase() {
    // 用户表
    db.run(`CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT UNIQUE NOT NULL,
        email TEXT UNIQUE NOT NULL,
        password TEXT NOT NULL,
        role TEXT DEFAULT 'user',
        is_verified BOOLEAN DEFAULT 0,
        verification_token TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )`);

    // 服务器实例表
    db.run(`CREATE TABLE IF NOT EXISTS servers (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        user_id INTEGER,
        node_id INTEGER,
        docker_container_id TEXT,
        port INTEGER,
        status TEXT DEFAULT 'stopped',
        config TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users (id),
        FOREIGN KEY (node_id) REFERENCES nodes (id)
    )`);

    // 节点表
    db.run(`CREATE TABLE IF NOT EXISTS nodes (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        host TEXT NOT NULL,
        port INTEGER DEFAULT 22,
        username TEXT NOT NULL,
        password TEXT,
        private_key TEXT,
        status TEXT DEFAULT 'offline',
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )`);

    // 系统设置表
    db.run(`CREATE TABLE IF NOT EXISTS settings (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        key TEXT UNIQUE NOT NULL,
        value TEXT NOT NULL,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )`);

    // API密钥表
    db.run(`CREATE TABLE IF NOT EXISTS api_keys (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        key TEXT UNIQUE NOT NULL,
        user_id INTEGER,
        description TEXT,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        expires_at DATETIME,
        is_active BOOLEAN DEFAULT 1,
        FOREIGN KEY (user_id) REFERENCES users (id)
    )`);

    console.log('数据库初始化完成');
}

// 路由导入
const authRoutes = require('./routes/auth');
const serverRoutes = require('./routes/servers');
const nodeRoutes = require('./routes/nodes');
const settingsRoutes = require('./routes/settings');
const apiRoutes = require('./routes/api');

// 路由使用
app.use('/auth', authRoutes);
app.use('/servers', serverRoutes);
app.use('/nodes', nodeRoutes);
app.use('/settings', settingsRoutes);
app.use('/api', apiRoutes);

// 主页路由
app.get('/', (req, res) => {
    if (req.session.user) {
        res.redirect('/dashboard');
    } else {
        res.redirect('/login');
    }
});

// 仪表板路由
app.get('/dashboard', (req, res) => {
    if (!req.session.user) {
        return res.redirect('/login');
    }
    res.render('dashboard', { user: req.session.user });
});

// 登录页面
app.get('/login', (req, res) => {
    if (req.session.user) {
        return res.redirect('/dashboard');
    }
    res.render('login');
});

// 注册页面
app.get('/register', (req, res) => {
    if (req.session.user) {
        return res.redirect('/dashboard');
    }
    res.render('register');
});

// 初始化页面
app.get('/init', (req, res) => {
    // 检查是否已经初始化
    db.get("SELECT COUNT(*) as count FROM users", (err, row) => {
        if (err) {
            return res.status(500).send('数据库错误');
        }
        if (row.count > 0) {
            return res.redirect('/login');
        }
        res.render('init');
    });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`Minecraft面板服务器运行在端口 ${PORT}`);
    initDatabase();
});

module.exports = { app, db };